/*
 * @desc 弹框组件
 * 基础定义 坐标点(x, y)
 * 当前位置point，当前行列矩阵--
 * 定义方向键--上下左右键切换坐标点，enter键有两个功能--1该坐标点有值时切换下一个坐标点，2该坐标点无值时执行该坐标点自定义事件
 * 方法：next
 */
import Vue from 'vue'

class KeyUp {
  constructor () {
    this.nodes = {}
    this.position = ''
  }

  next () {
    if (this.nodes[this.position].end) {
      this.position = 'x' + (this.nodes[this.position].position.x + 1) + 'y' + 0
    } else {
      this.position = 'x' + this.nodes[this.position].position.x + 'y' + (this.nodes[this.position].position.y + 1)
    }
    if (this.nodes[this.position]) {
      this.nodes[this.position].node.focus()
    } else {
      this.next()
    }
  }
}

const keyup = new KeyUp()

Vue.directive('keyboard', {
  bind: function (el, binding, vnode) {
    // 第一次绑定要做
    // 写入矩阵数组
    let node = vnode.componentInstance ? vnode.componentInstance : vnode.elm
    keyup.nodes['x' + binding.value.x + 'y' + binding.value.y] = {
      node: node,
      position: {x: binding.value.x, y: binding.value.y},
      end: binding.value.end || false
    }
    if (vnode.componentInstance) {
      console.log(vnode.componentInstance)
      vnode.componentInstance.$on('keyup', function (e) { console.log(e) })
    } else {
      vnode.elm.addEventListener('keyup', function (e) {
        console.log(e)
      })
    }
    // console.log(keyup)
  },
  unbind: function (el, binding, vnode) {
    delete keyup.nodes['x' + binding.value.x + 'y' + binding.value.y]
  }
})
